package com.kehao.accountbook;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kehao.accountbook.network.Network;
import com.kehao.accountbook.network.TwoCaseCallBack;
import com.kehao.accountbook.pojo.Expenditure;

import org.litepal.LitePal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccountApplication extends Application {
    private boolean loginstatus = false;
    private String username =null;
    private String password = null;
    public static boolean rempwd;
    private boolean mode = false;
    SQLiteDatabase db;
    @Override
    public void onCreate() {
        super.onCreate();
        LitePal.initialize(this);
        db = LitePal.getDatabase();
    }

    //同步本地和网上的数据
    public void syncData(final int year ,final int month){
        Map<String,Object> map = new HashMap<>();
        map.put("username",username);//传输用户名
        map.put("year",year);
        map.put("month",month);
        List<Expenditure> list1 = LitePal.where("username = ? and status <9",username).find(Expenditure.class);
        String listJson = new Gson().toJson(list1);
        map.put("list",listJson);//需要在服务器更新的数据
        int maxAnchor = LitePal.max(Expenditure.class,"anchor",int.class);
        map.put("anchor",maxAnchor);
        /*找出客户端中更新过的最大的上次更新的时间(anchor) 不是列表中的（列表中可能全是新添加的项目）
        新添加的项目的上次更新时间是0，所以必须找打最大值，以免以为数据全部需要同步到客户端*/
        String json =new Gson().toJson(map);
        Network network = new Network(new TwoCaseCallBack() {
            @Override
            public void success(String json) {
                Map map = new Gson().fromJson(json,new TypeToken<Map>(){}.getType());
                int modify = (int)(double)map.get("modify");
                String listStr = (String) map.get("list");//需要同步到本地的数据
                List<Expenditure> listFromInternet = new Gson().fromJson(listStr,new TypeToken<List<Expenditure>>(){}.getType());
                List<Expenditure> list = LitePal.where("username = ? and status <9",username).find(Expenditure.class);
                //对本地数据更新
                for(Expenditure i :list){
                    switch (i.getStatus()){
                        case Expenditure.STATUS_ADD:
                        case Expenditure.STATUS_LOCAL_CHANGE:
                            i.setStatus(Expenditure.STATUS_SYNC);
                            i.setAnchor(modify);
                            i.save();
                            break;
                        case Expenditure.STATUS_REMOVE:
                            i.delete();
                            break;
                    }
                }
                //添加或更新服务器来的数据
                for(Expenditure i :listFromInternet){
                    List<Expenditure> list1 = LitePal.where("username = ? and year = ? and month = ? and day = ? " +
                                    "and hour = ? and min = ? and second = ?", username,Integer.toString(year),Integer.toString(month),
                            Integer.toString(i.getDay()),Integer.toString(i.getHour()),Integer.toString(i.getMin()),Integer.toString(i.getSecond()))
                            .find(Expenditure.class);
                    if(list1.size()==0){//本地没有这个数据，添加
                        i.save();
                    }else {//本地有了 更新
                        list1.get(0).setAnchor(i.getAnchor());
                        list1.get(0).setType(i.getType());
                        list1.get(0).setMoney(i.getMoney());
                        list1.get(0).setComment(i.getComment());
                    }
                }
                if(Network.handler!=null){
                    Message message = new Message();
                    message.what=2;
                    Network.handler.sendMessage(message);
                }
            }

            @Override
            public void fail() {

            }
        }, json, "http://192.168.0.110:8080/account/sync", this);
        network.send();
    }

    public void modeOnline(){
        mode = true;
    }

    public void modeOffline(){
        mode = false;
    }

    public boolean NetworkMode(){
        return mode;
    }


    public static boolean isRempwd() {
        return rempwd;
    }

    public static void setRempwd(boolean rempwd) {
        AccountApplication.rempwd = rempwd;
    }

    public boolean isLoginstatus() {
        return loginstatus;
    }

    public void setLoginstatus(boolean loginstatus) {
        this.loginstatus = loginstatus;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
